﻿/*
@author liuzj
MeasureLength 测距
*/
define(["dojo/_base/declare"], function (declare) {
    var instance = declare(null, {});
    //订阅消息
    instance.action = function (map){
	require(["esri/Color","esri/layers/GraphicsLayer", "esri/graphic", "esri/geometry/Point", "esri/geometry/Polyline", "dojo/on",  "esri/toolbars/draw","esri/symbols/TextSymbol","esri/symbols/SimpleMarkerSymbol","esri/symbols/SimpleLineSymbol", "esri/symbols/PictureMarkerSymbol","esri/geometry/mathUtils"], function ( Color,GraphicsLayer,Graphic, Point, Polyline, on,Draw,TextSymbol,MarkerSymbol,SimpleLineSymbol,PictureMarkerSymbol,mathUtils) {
		//debugger
		/**测距graphicLayer图层*/
		var meatureDistanceLayer = new GraphicsLayer();
		//存储所有graphic图层
		ioc.map.graphiclayers.push(meatureDistanceLayer);
		map.addLayer(meatureDistanceLayer);
		/**转折点符号*/
		var thispointsymble=new MarkerSymbol().setSize(9).setOutline(new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([255, 0, 0]), 1),3).setColor(new Color([255, 255, 255, 1]));
		/**线符号*/
		var thispolylinesymble = new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID,new Color([251, 126, 67]),3);
		/**生成随机数*/
		var suijishu=new Date().getTime();
		
        var lastMapPoint = null;
        var showPt = null;
        var isfinish = 0;
        var polyLine = new Polyline();
       
       
        var isdb = false;//区分单击和双击
        /**在map上双击事件*/
        var  mapDoubleClickEvent = on(map, "dbl-click", function (evt) {
        	//debugger
            var graphic = new Graphic(evt.mapPoint, thispointsymble);
            graphic.bType = "MeasureLength"+suijishu;
            meatureDistanceLayer.add(graphic);
            isdb = true;
        });
        /**在map上单击事件*/
        var measureEvent = on(map, "click", function (evt) {
            //remove listener after first event
        	//debugger
            isdb = false;
            setTimeout(function(){
                if (isdb != false){
                    //移除双击事件
                    if (mapDoubleClickEvent != null) {
                        mapDoubleClickEvent.remove();
                    }
                    return;
                }
                //点击处的点符号graphic对象
                var graphic = new Graphic(evt.mapPoint, thispointsymble);
                graphic.bType = "MeasureLength"+suijishu;
                meatureDistanceLayer.add(graphic);
                
                if (lastMapPoint == null) {//标注起点备注
                    lastMapPoint = evt.mapPoint;
                    addResult(lastMapPoint, "起点");
                }else {//非起点--就会直线
                    polyLine.spatialReference = map.spatialReference;
                    polyLine.addPath([lastMapPoint, evt.mapPoint, evt.mapPoint]);
                    showPt = evt.mapPoint;
                    lastMapPoint = evt.mapPoint;
                }
            }, 500);
        });
       
		/**添加文本标注———起点和结束点*/
	    function addResult(point, text) {
            //添加起点标识
            require(["esri/symbols/TextSymbol", "esri/symbols/PictureMarkerSymbol"], function (TextSymbol, PictureMarkerSymbol) {
                var len = strLength(text) * 5 + 20;
                //文本符号graphic对象
                var symbol = new TextSymbol(text).setColor(new Color([255, 0, 0]));//文本的符号
                symbol.setOffset(len / 2 + 20, -5); //符号的偏移
                var graphic = new Graphic(point, symbol);
                graphic.bType = "MeasureLength"+suijishu;
                
                //图片符号graphic对象
               /* var pictureSymbol = new PictureMarkerSymbol({
                        "url": "gistech/widgets/ManageTools/images/measure_bg.png",
                        "height": 15,
                        "width": len,
                        "type": "esriPMS",
                        "xoffset": len / 2 + 10,
                        "yoffset": 0
						});
                var graphicB = new Graphic(point, pictureSymbol);
                graphicB.bType = "MeasureLength"+suijishu;
                
                //添加 graphic对象
                meatureDistanceLayer.add(graphicB);*/
                meatureDistanceLayer.add(graphic);
            });
        }
	    function strLength(str) {
	        var realLength = 0, len = str.length, charCode = -1;
	        for (var i = 0; i < len; i++) {
	            charCode = str.charCodeAt(i);
	            if (charCode >= 0 && charCode <= 128) realLength += 1;
	            else realLength += 2;
	        }
	        return realLength;
	    }
        /**绘制线*/
        var drawTool =new Draw(map);
        drawTool.activate(Draw["POLYLINE"]);
        var drawEndEvent =on(drawTool,"draw-end", function (evt) {
        	debugger
            isfinish = 1;
        	//移除单击事件
            if (measureEvent != null) {
                measureEvent.remove();
            }
            //移除双击事件
            if (mapDoubleClickEvent != null) {
            	mapDoubleClickEvent.remove();
            }
            //注销绘制工具
            drawTool.deactivate();
            map.setMapCursor("default");
            
            
            var geometry = evt.geometry;
            var length = geometry.paths[0].length;
            //最后的终点
            showPt = new Point(geometry.paths[0][length - 1], map.spatialReference);
            
            //整个折线
            var graphic = new Graphic(geometry, thispolylinesymble);
            graphic.bType = "MeasureLength"+suijishu;
            meatureDistanceLayer.add(graphic);
            
            //计算整个折线的距离
            var alllength=0;
            for(var i=1;i<length;i++)
            	{
                	var startpoint =new Point(geometry.paths[0][i-1], map.spatialReference);
                	var endpoint =new Point(geometry.paths[0][i], map.spatialReference);
            		alllength=alllength+mathUtils.getLength(startpoint,endpoint);
            	}
            drawfinish(alllength);
            drawEndEvent.remove();
            //绘制完成移除地图注册的事件
        });
        //测距完成响应事件
        function drawfinish(length){
        	 debugger
        	 var lengthtext = "";
        	 if (length < 1000) {
        		 lengthtext = "总长：" + (length).toFixed(1) + "米";
             }
             else {
            	 lengthtext = "总长：" + (length/1000).toFixed(3) + "公里";
             }
        	 if (isfinish == 1) {
                 //增加一个关闭的事件
                 var closeSymbol = new PictureMarkerSymbol({
                     "url": "gistech/widgets/ManageTools/images/measure_close.png",
                     "height": 12,
                     "width": 12,
                     "type": "esriPMS",
                     "xoffset": 3,
                     "yoffset": -10
                 });
                 var closeGraphic = new Graphic(showPt, closeSymbol);
                 console.log(showPt)
                 
                 closeGraphic.bType = "MeasureLength"+suijishu;
                 console.log(closeGraphic);
                 meatureDistanceLayer.add(closeGraphic);
                 var closeEvent=on(meatureDistanceLayer, "click", function (evt) {
                	 for( var i=meatureDistanceLayer.graphics.length - 1;i>=0;i--){
                    	 if (evt.graphic.bType ==meatureDistanceLayer.graphics[i].bType) {
                    		 meatureDistanceLayer.remove(meatureDistanceLayer.graphics[i]);
                         }
                    }
                 });
             }
             addResult(showPt, lengthtext);
             showPt = null;
        }
	  });
	}
    return instance;
});